package com.cuit.qx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cuit.qx.aop.OperLog;
import com.cuit.qx.bean.*;
import com.cuit.qx.service.*;
import com.cuit.qx.utils.ReturnData;
import com.cuit.qx.utils.ReturnStateCode;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

import static org.thymeleaf.util.ListUtils.isEmpty;

/**
 * @Author:wjd
 * @Description:
 * @date:Created in 15:14 2020/9/21
 * @Modified By:
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/warning")
public class WarningController {

    @Autowired
    WarningService warningService;
    @Autowired
    private TemScaleService temScaleService;
    @Resource
    private WarningRainService warningRainService;
    @Resource
    private WarningWindService warningWindService;

    /**
     * 根据id修改报警信息
     *
     * @param stationId 站点id
     * @return
     */
    @RequestMapping(value = "/updateWarningList", method = RequestMethod.GET)
    @OperLog(operModul = "报警管理", operType = "3", operDesc = "根据id修改报警信息")
    @ResponseBody
    public ReturnData updateWarningList(String stationId) {
        int num = warningService.updateWarningById(stationId);
        if (num > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
    }

    /**
     * 分页查询全部数据
     *
     * @param pageNo       当前页数
     * @param pageSize     每页条数
     * @param warningState 预警状态  1:未确认  0:已确认
     * @return
     */
    @RequestMapping(value = "/getWarningList", method = RequestMethod.GET)
//    @OperLog(operModul = "预警管理", operType = "1", operDesc = "分页查询全部数据")
    @ResponseBody
    public ReturnData getWarningList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize, String warningState) {
        //所有为确认的报警数据，供gis使用
        List<Warning> list = warningService.getWarningListWithState();

        //报警记录，供前端列表展示使用
        IPage<Warning> warnings = warningService.getWarningList(pageNo, pageSize, warningState);
        if (!isEmpty(warnings.getRecords())) {
            // 将long类型转为Integer
            long total = warnings.getTotal();
            String str = String.valueOf(total);
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), Integer.parseInt(str), list, warnings.getRecords());
        } else {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEEBUT.getMsg(), (int) warnings.getTotal(), new ArrayList(), new ArrayList());
        }
    }

    /**
     * 历史告警数据查询
     *
     * @param pageNo        当前页数
     * @param pageSize      每页条数
     * @param stationName   站名
     * @param stationNumber 站号
     * @param address       地址
     * @param warningState  报警状态
     * @param startTime     开始时间
     * @param endTime       结束时间
     * @return
     */
    @RequestMapping(value = "/getQueryWarningList", method = RequestMethod.GET)
    @ResponseBody
    public ReturnData getQueryWarningList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                          String stationName, String stationNumber, String address, String warningState, String startTime, String endTime) {

        //分页
        IPage<Warning> warnings = warningService.getQueryWarningList(pageNo, pageSize, stationName, stationNumber, address, warningState, startTime, endTime);

        if (!isEmpty(warnings.getRecords())) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), (int) warnings.getTotal(), warnings.getRecords());
        } else {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEEBUT.getMsg(), (int) warnings.getTotal(), new ArrayList());
        }
    }

    /**
     * 根据时间段查询各站点预警条数
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    @RequestMapping(value = "/getWarningNum", method = RequestMethod.GET)
    @ResponseBody
    public ReturnData getWarningNum(String startTime, String endTime) {
        List<Warning> warnings = warningService.getWarning(startTime, endTime);
        if (warnings != null) {
            ArrayList<HashMap<String, Object>> data = new ArrayList<>();
            for (Warning warning : warnings) {
                HashMap<String, Object> map = new HashMap<>();
                String stationNumber = warning.getStationNumber();
                int num = warningService.getWarningNum(stationNumber, startTime, endTime);
                map.put("站名", warning.getStationName());
                map.put("站号", warning.getStationNumber());
                map.put("站点地址", warning.getStationSite());
                map.put("count", num);
                data.add(map);
            }
            // 去重获取的结果
            HashSet<HashMap<String, Object>> dataSet = new HashSet<>(data);
            data.clear();
            data.addAll(dataSet);
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), data);
        } else {
            return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
        }
    }

    /**
     * 根据预警id删除预警信息
     *
     * @param id 预警id
     * @return
     */
    @RequestMapping(value = "/deleteWarningById", method = RequestMethod.GET)
    @ResponseBody
    public ReturnData deleteWarningById(String id) {
        boolean flag = warningService.removeById(id);
        if (flag) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
        } else {
            return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
        }
    }


    /**
     * 根据多个预警id删除预警信息
     *
     * @param map 预警ids
     * @return
     */
    @RequestMapping(value = "/deleteWarningByIds", method = RequestMethod.POST)
    @ResponseBody
    public ReturnData deleteWarningByIds(@RequestBody Map<String, String> map) {
        String ids = map.get("ids");
        int num = warningService.deleteWarningByIds(ids);
        if (num > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), "删除失败或者是未确认的预警");
        }
    }


    /**
     * 根据时间段来删除预警信息
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    @RequestMapping(value = "/deleteWarningByTime", method = RequestMethod.GET)
    @ResponseBody
    public ReturnData deleteWarningByTime(String startTime, String endTime) {
        int num = warningService.deleteWarningByTime(startTime, endTime);
        return new ReturnData(ReturnStateCode.SUCCEE.getCode(), "删除成功，已删除" + num + "条已确认预警，未确认预警不能删除");
    }


    /**
     * 导出预警信息,  按日,周,月导出
     *
     * @param res
     * @param req
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param flag      导出类型  1:日报  2:周报  3:月报
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/exportXlsWarning", method = RequestMethod.GET)
    public ModelAndView exportXlsWarning(HttpServletResponse res, HttpServletRequest req, String startTime, String endTime, String flag) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<Warning> warningList = new ArrayList<>();
        // 日报数据
        if ("1".equals(flag)) {
            QueryWrapper<Warning> queryWrapper = new QueryWrapper<>();
            queryWrapper.likeRight("create_time", startTime.split(" ")[0]);
            warningList = warningService.list(queryWrapper);
        }
        // 周报数据
        if ("2".equals(flag)) {
            if ((startTime != null && !("".equals(startTime))) && (endTime != null && !("".equals(endTime)))) {
                QueryWrapper<Warning> queryWrapper = new QueryWrapper<>();
                queryWrapper.ge("create_time", startTime).le("create_time", endTime);
                warningList = warningService.list(queryWrapper);
            }
        }
        // 月报数据
        if ("3".equals(flag)) {
            if ((startTime != null && !("".equals(startTime))) && (endTime != null && !("".equals(endTime)))) {
                QueryWrapper<Warning> queryWrapper = new QueryWrapper<>();
                queryWrapper.ge("create_time", startTime).le("create_time", endTime);
                warningList = warningService.list(queryWrapper);
            }
        }
        // 导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME,  new String("预警信息".getBytes(),"UTF-8"));
        mv.addObject(NormalExcelConstants.CLASS, Warning.class);
        ExportParams exportParams = new ExportParams("预警信息数据", "导出人:" + user.getUsername(), "预警管理");
        exportParams.setImageBasePath("");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, warningList);
        return mv;
    }

    /**
     * 预警历史 风力查询
     *
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @param addrCounty 县域
     * @param orderType  time:时间排序  wind：风力大小
     * @return
     */
    @RequestMapping(value = "/getQueryWarningWind", method = RequestMethod.GET)
    @ResponseBody
    public ReturnData getQueryWarningWind(String startTime, String endTime, String addrCounty, String orderType) {
        List<WarningWindExport> warningwindList = warningService.selectWind(startTime, endTime, addrCounty, orderType);

        if (!isEmpty(warningwindList)) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), warningwindList.size(), warningwindList);
        } else {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEEBUT.getMsg(), warningwindList.size(), new ArrayList());
        }
    }

    /**
     * 预警风力导出
     *
     * @param startTime
     * @param endTime
     * @param addrCounty
     * @param orderType
     * @param res
     * @param req
     * @return
     */
    @RequestMapping(value = "/exportXlsTemplate", method = RequestMethod.GET)
    public ModelAndView exportXlsTemplate(String startTime, String endTime, String addrCounty, String orderType,
                                          HttpServletResponse res, HttpServletRequest req) throws IOException {
        //User user = (User) req.getSession().getAttribute("user");
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<WeatherStation> sysUsers = new ArrayList<WeatherStation>();
        WeatherStation c = new WeatherStation();
        c.setStationType("0代表自建站1代表气象站");
        sysUsers.add(c);
        List<WarningWindExport> warningwindList = warningService.selectWind(startTime, endTime, addrCounty, orderType);

        mv.addObject(NormalExcelConstants.FILE_NAME,  new String("预警最大风力".getBytes(),"UTF-8"));
        mv.addObject(NormalExcelConstants.CLASS, WarningWindExport.class);
        ExportParams exportParams = new ExportParams("预警最大风力导出", "导出人", "导出数据");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, warningwindList);
        return mv;
    }


    /**
     * 查询等级
     *
     * @param element 要素名称   气温:tem  降水:rain  风力:wind
     * @return
     */
    @RequestMapping(value = "/getScale", method = RequestMethod.GET)
    @ResponseBody
    @OperLog(operModul = "等级管理", operType = "1", operDesc = "查询等级")
    public ReturnData getScale(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, String element) {
        if (element != null) {
            // 查询气温等级
            if ("tem".equals(element)) {
                IPage<TemScale> queryTem = new Page<>(pageNo, pageSize);
                IPage<TemScale> page = temScaleService.page(queryTem);
                if (!isEmpty(page.getRecords())) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), (int) page.getTotal(), page.getRecords());
                } else {
                    return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
                }
            }
            // 查询降雨等级
            if ("rain".equals(element)) {
                IPage<WarningRain> queryRain = new Page<>(pageNo, pageSize);
                IPage<WarningRain> page = warningRainService.page(queryRain);
                if (!isEmpty(page.getRecords())) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), (int) page.getTotal(), page.getRecords());
                }
                return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
            }
            // 查询风力等级
            if ("wind".equals(element)) {
                IPage<WarningWind> queryWind = new Page<>(pageNo, pageSize);
                IPage<WarningWind> page = warningWindService.page(queryWind);
                if (!isEmpty(page.getRecords())) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), (int) page.getTotal(), page.getRecords());
                }
                return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
            }
        } else {
            return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
        }
        return null;
    }


    /**
     * 新增等级
     *
     * @param scaleModel
     * @return
     */
    @RequestMapping(value = "/addScale", method = RequestMethod.POST)
    @ResponseBody
    @OperLog(operModul = "气温管理", operType = "2", operDesc = "新增等级")
    public ReturnData addScale(@RequestBody ScaleModel scaleModel) {
        String element = scaleModel.getElement();
        String threshold = scaleModel.getThreshold();
        String color = scaleModel.getColor();
        Integer hour = scaleModel.getHour();
        // 风力类型 只针对风力使用
        Integer windType = scaleModel.getType();

        if (element != null) {
            if ("tem".equals(element)) {
                TemScale temScale = new TemScale();
                temScale.setThreshold(threshold);
                temScale.setColor(color);
                temScale.setHour(hour);
                boolean save = temScaleService.save(temScale);
                if (save) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
                } else {
                    return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
                }
            }
            if ("rain".equals(element)) {
                WarningRain warningRain = new WarningRain();
                warningRain.setThreshold(threshold);
                warningRain.setColor(color);
                warningRain.setHour(hour);
                boolean save = warningRainService.save(warningRain);
                if (save) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
                } else {
                    return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
                }
            }
            if ("wind".equals(element)) {
                WarningWind warningWind = new WarningWind();
                warningWind.setThreshold(threshold);
                warningWind.setColor(color);
                warningWind.setHour(hour);
                warningWind.setType(windType);
                boolean save = warningWindService.save(warningWind);
                if (save) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
                } else {
                    return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
                }
            }
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
        return null;
    }

    /**
     * 修改等级
     *
     * @param scaleModel
     * @return
     */
    @RequestMapping(value = "/updateScale", method = RequestMethod.POST)
    @ResponseBody
    @OperLog(operModul = "气温管理", operType = "3", operDesc = "修改等级")
    public ReturnData updateScale(@RequestBody ScaleModel scaleModel) {
        String element = scaleModel.getElement();
        Integer id = scaleModel.getId();
        String threshold = scaleModel.getThreshold();
        String color = scaleModel.getColor();
        Integer hour = scaleModel.getHour();
        // 风力等级 只针对风力使用
        Integer windType = scaleModel.getType();

        if (element != null && id != null) {
            if ("tem".equals(element)) {
                TemScale temScale = new TemScale();
                temScale.setId(id);
                temScale.setThreshold(threshold);
                temScale.setColor(color);
                temScale.setHour(hour);
                boolean save = temScaleService.updateById(temScale);
                if (save) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
                } else {
                    return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
                }
            }
            if ("rain".equals(element)) {
                WarningRain warningRain = new WarningRain();
                warningRain.setId(id);
                warningRain.setThreshold(threshold);
                warningRain.setColor(color);
                warningRain.setHour(hour);
                boolean save = warningRainService.updateById(warningRain);
                if (save) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
                } else {
                    return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
                }
            }
            if ("wind".equals(element)) {
                WarningWind warningWind = new WarningWind();
                warningWind.setId(id);
                warningWind.setThreshold(threshold);
                warningWind.setColor(color);
                warningWind.setHour(hour);
                warningWind.setType(windType);
                boolean save = warningWindService.updateById(warningWind);
                if (save) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
                } else {
                    return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
                }
            }
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
        return null;
    }

    /**
     * 删除等级
     *
     * @param element 要素名称
     * @param id      要素id
     * @return
     */
    @RequestMapping(value = "/deleteScale", method = RequestMethod.GET)
    @ResponseBody
    @OperLog(operModul = "气温管理", operType = "4", operDesc = "删除等级")
    public ReturnData deleteScale(String element, Integer id) {

        if (element != null && id != null) {
            if ("tem".equals(element)) {
                boolean save = temScaleService.removeById(id);
                if (save) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
                } else {
                    return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
                }
            }
            if ("rain".equals(element)) {
                boolean save = warningRainService.removeById(id);
                if (save) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
                } else {
                    return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
                }
            }
            if ("wind".equals(element)) {
                boolean save = warningWindService.removeById(id);
                if (save) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
                } else {
                    return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
                }
            }
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
        return null;
    }

//    @RequestMapping(value = "/getWarningListContent", method = RequestMethod.GET)
//    @OperLog(operModul = "预警管理", operType = "1", operDesc = "查询报警状态为1时的报警内容")
//    @ResponseBody
//    public ReturnData getWarningListContent() {
//        List<String> warningListContent = warningService.getWarningListContent();
//        if (!isEmpty(warningListContent)) {
//            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), warningListContent);
//        } else {
//            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
//        }
//    }
}
